<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Review & Rating Synthesis
 * @version 	1.0.2
 * @author 		Rukan <rukanhitokiri@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://www.zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

include_once(dirname(__FILE__).'/classes/ZProductReview.php');
include_once(dirname(__FILE__).'/classes/ZprofessConfigure.php');

class AdminZProductReview extends AdminTab
{
	public function __construct()
	{
		global $cookie;
	 	$this->table = 'zproduct_review';
		$this->identifier = 'id_zproduct_review';
	 	$this->className = 'ZProductReview';
	 	$this->lang = false;
	 	$this->delete = true;

		$status = ZProductReview::getStatusTypes();
		$this->_select = "pl.name AS product_name, round(a.rating, 1) as rating";
		$this->fieldsDisplay = array(
			'id_zproduct_review'     	=> array('width' => 25,  'title' => $this->l('ID'), 'align' => 'center'),
			'product_name' 	  			=> array('width' => 140, 'title' => $this->l('Product Name'), 'filter_key' => 'pl!name'),
			'title' 	  				=> array('width' => 140, 'title' => $this->l('Title'), 'maxlength' => 120),
			'customer_name'				=> array('width' => 100,  'title' => $this->l('Customer Name')),
			'rating'					=> array('width' => 40,  'title' => $this->l('Rating'), 'align' => 'center', 'prefix' => '<div style="color:red;font-weight:bold;font-size:12px;">', 'suffix' => '</div>'),
			'status' 					=> array('width' => 40,	 'title' => $this->l('Status'), 'align' => 'center', 'icon' => array(2 => 'enabled.gif', 0 => 'disabled.gif', 'default' => 'news-new.gif'), 'orderby' => false, 'type' => 'select', 'select' => $status, 'filter_key' => 'a!status'),
			'date_add' 					=> array('width' => 30,	 'title' => $this->l('Date'), 'type' => 'date', 'align' => 'right'),
	 	);
	 	$this->_join ='LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (a.id_product=pl.id_product AND pl.id_lang='.$cookie->id_lang.')';
	 	
	 	parent::__construct();
	}
	
	private function _renderJS()
	{
		return '
		<script type="text/javascript" src="'._MODULE_DIR_.'reviewratingsynthesis/js/raty/jquery.raty.min.js"></script>';
	}
	
	/**
	 * 
	 * @param string $label
	 * @param string $name
	 * @param boolean $required
	 * @return string
	 */
	private function _displayFieldText($label, $name, $required = true) 
	{
		if (!($obj = $this->loadObject(true)))
			return;
			
		echo '
		<label>'.$this->l($label).'</label>
	    <div class="margin-form">
	      	<input type="text" size="40" name="'.$name.'" value="'.htmlentities($this->getFieldValue($obj, $name), ENT_COMPAT, 'UTF-8').'" />'.($required ? '<sup> *</sup>' : '').'
	    </div>
	    <div class="clear"></div>';
	}
	
	/**
	 * 
	 * @param string $label
	 * @param string $name
	 * @param boolean $required
	 * @return string
	 */
	private function _displayTextarea($label, $name, $required = false) 
	{
		if (!($obj = $this->loadObject(true)))
			return;
		
		echo '	
		<label>'.$this->l($label).' </label>
		<div class="margin-form">
			<textarea name="'.$name.'" rows="10" cols="100">'.htmlentities($this->getFieldValue($obj, $name), ENT_COMPAT, 'UTF-8').'</textarea>'.($required ? ' <sup> *</sup>' : '').'
		</div>
		<div class="clear"></div>';
	}
	
	/**
	 * Manage page processing
	 * @view AdminTab::postProcess()
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
//	public function postProcess()
//	{
//		//echo '<pre>';var_dump($_POST);die();
//	}
	
	/**
	 * Display form
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function displayForm($isMainTab = true)
	{
		global $currentIndex, $cookie;
		parent::displayForm();
		
		if (!($obj = $this->loadObject(true)))
			return;
		
		ZprofessConfigure::getRatingConfig();
			
		$id_customer	= $this->getFieldValue($obj, 'id_customer');
		$customerName 	= $this->getFieldValue($obj, 'customer_name');
		$email 			= $this->getFieldValue($obj, 'email');
		$ProductId 		= $this->getFieldValue($obj, 'id_product');
		$productName 	= ZProductReview::getNameProductById($ProductId);
		$dateAdd 		= $this->getFieldValue($obj, 'date_add');
		$status 		= $this->getFieldValue($obj, 'status');
		$idGuest 		= $this->getFieldValue($obj, 'id_guest');
		$rating 		= $this->getFieldValue($obj, 'rating');
		$reply_employees = $this->getFieldValue($obj, 'reply_employees');
		$employess = new EmployeeCore ($cookie->id_employee);
		if ($this->getFieldValue($obj, 'name_employees')=='')
			$name_employee = $employess->firstname." ".$employess->lastname;
		else 
			$name_employee = $this->getFieldValue($obj, 'name_employees');
		echo $this->_renderJS().'
		<form action="'.$currentIndex.'&submitAdd'.$this->table.'=1&token='.$this->token.'" method="post" enctype="multipart/form-data">
		'.($obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" />' : '');

		echo '<div style="float:left" style="width:440px">
			<h2>'.$this->l('Customer review & rating from').' '.Tools::displayDate($dateAdd, (int)$cookie->id_lang, true).'</h2>
			<div style="width:429px">
				<img src="../img/admin/disabled.gif" alt="'.$this->l('Cancel').'" /> '.$this->l('Cancel').' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				<img src="../img/admin/news-new.gif" alt="'.$this->l('Pending').'" /> '.$this->l('Pending').' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				<img src="../img/admin/enabled.gif" alt="'.$this->l('Pending').'" /> '.$this->l('Accept').'
			</div>
			<div class="clear">&nbsp;</div>';
	
			/* Display current date & status */
			echo '
			<table cellspacing="0" cellpadding="0" class="table" style="width: 429px">
				<tr>
					<th>'.Tools::displayDate($dateAdd, (int)$cookie->id_lang, true).'</th>
					<th><img src="../img/admin/'.(($status == 1) ? 'news-new.gif' : (($status == 0) ? 'disabled.gif' : 'enabled.gif')).'" /></th>
					<th>'.ZProductReview::displayStatusType($status).'</th>
				</tr>
			</table>
			<br />';
			
			/*Display rating*/
			if(!Configuration::get('ZPRO_ONLY_REVIEW')) {
				$criterions = ZProductCriterion::getCriterionByProduct($ProductId, (int)$cookie->id_lang);
				$averages = ZProductReview::getRatingByReview($obj->id);
				$configRating = ZprofessConfigure::$configRating;
				echo '<img src="'._MODULE_DIR_.'reviewratingsynthesis/logo.gif" /> '.$this->l('Rating').'<br />';
				foreach ($criterions as $criterion) {
					foreach ($averages as $average) {
						if ($criterion['id_zproduct_criterion'] == $average['id_zproduct_criterion']) {
							echo '
							<div style="margin:5px 10px;">
								<b>'.$criterion['name'].': ('.round($average['rating'], 1).') </b>
								<div class="displayAverageZprofess_'.$average['id_zproduct_criterion'].'"></div>
								<script type="text/javascript">
									$(".displayAverageZprofess_'.$average['id_zproduct_criterion'].'").raty({									
										width: 			'.$configRating['width'].',
										cancel: 		'.$configRating['cancel'].',						
										cancelHint:   	"'.$configRating['cancelHint'].'",  
										cancelOff:  	"'.$configRating['cancelOff'].'",
										cancelOn:   	"'.$configRating['cancelOn'].'", 	
										cancelPlace:  	"'.$configRating['cancelPlace'].'", 
									
										half:  			'.$configRating['half'].',
										hintList:		'.$configRating['hintList'].',
										noRatedMsg:		"'.$configRating['noRatedMsg'].'",
										number:     	'.$configRating['number'].',
										path:           "'.$configRating['path'].'",	
										iconRange:      '.$configRating['iconRange'].',
										starHalf:		"'.$configRating['starHalf'].'",
										starOff:		"'.$configRating['starOff'].'",
										starOn:			"'.$configRating['starOn'].'",
										readOnly:		true,
										start: 			'.round($average['rating'], 1).',
									});
								</script>
							</div>';
						}
					}
				}
			} else {
				echo '<img src="'._MODULE_DIR_.'reviewratingsynthesis/logo.gif" /> '.$this->l('Rating').'<br />';
				echo '<div style="margin:5px 10px;">You have config: Just text reviews alone, no rating</div>';	
			}
			
			echo'</div>';
		
		/* Display general information about product*/
		$tokenProduct = Tools::getAdminToken('AdminCatalog'.(int)(Tab::getIdFromClassName('AdminCatalog')).(int)($cookie->id_employee));
		echo '
			<div style="float: left; margin-left: 40px">
			<fieldset style="width: 400px">
				<legend><img src="../img/admin/cart.gif" /> '.$this->l('Product').'</legend>
				<span style="font-weight: bold;">
				<a href="?tab=AdminCatalog&id_product='.$ProductId.'&updateproduct&token='.$tokenProduct.'"> '.$productName.'</a></span>
				<br /><br />
				<input type="hidden" name="id_product" value="'.$ProductId.'" />
			</fieldset>
			<br style="clear:both;" />';
				/* Display general information about name & email customer*/
			$tokenCustomer = Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)($cookie->id_employee));
			echo '
				<fieldset style="width: 400px">
					<legend><img src="../img/admin/tab-customers.gif" /> '.$this->l('Customer').'</legend>
					<span style="font-weight: bold;">';
					if ($id_customer)
						echo '
						<a href="?tab=AdminCustomers&id_customer='.$id_customer.'&viewcustomer&token='.$tokenCustomer.'"> '.$customerName.'</a></span> ('.$this->l('#').$id_customer.')<br />
						(<a href="mailto:'.$email.'">'.$email.'</a>)';
					else {
						echo $customerName.'</span><br />'.
						($email ? '(<a href="mailto:'.$email.'">'.$email.'</a>)' : '<br />');
					}
			echo '	<input type="hidden" name="id_customer" value="'.$id_customer.'" />
					<input type="hidden" name="id_guest" value="'.$idGuest.'" />
					<input type="hidden" name="email" value="'.$email.'" />
				 	<input type="hidden" name="customer_name" value="'.$customerName.'" />
				 	<input type="hidden" name="date_add" value="'.$dateAdd.'" />
				 </fieldset>
				</div>';
		
		echo '<br style="clear:both;" />
			<fieldset style="margin-top:25px; width: 715px; "><legend><img src="../img/admin/contact.gif" />'.$this->l('Reviews & Ratings').'</legend>';
	
			$this->_displayFieldText('Website:', 'website');
			$this->_displayFieldText('Title:', 'title');
			$this->_displayTextarea('Content:', 'content', true);
		
		echo '	<label>'.$this->l('Status:').'</label>
		<div class="margin-form">
			<input type="radio" name="status" id="status_ac" value="2" '.(($status == 2) ? 'checked="checked" ' : '').'/>
			<label class="t" for="status_ac"><img src="../img/admin/enabled.gif" alt="'.$this->l('Accept').'" title="'.$this->l('Accept').'" /></label>
			<input type="radio" name="status" id="status_ca" value="0" '.(($status == 0) ? 'checked="checked" ' : '').'/>
			<label class="t" for="status_ca"><img src="../img/admin/disabled.gif" alt="'.$this->l('Cancel').'" title="'.$this->l('Cancel').'" /></label>
			<input type="radio" name="status" id="status_new" value="1" '.(($status == 1) ? 'checked="checked" ' : '').'/>
			<label class="t" for="status_new"><img src="../img/admin/news-new.gif" alt="'.$this->l('Pending').'" title="'.$this->l('Pending').'" /></label>
		</div>
		<div class="clear"></div>';
		
		echo '	<div class="margin-form">
					<input type="submit" value="'.$this->l('   Save   ').'" name="submitAdd'.$this->table.'" class="button" />
				</div>
				<div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
			</fieldset>
		
		<p class="clear"></p>';
		
		echo '
		<div>
			<form method="post" action="">
			<fieldset style="width: 764px;">
				<legend onclick="$(\'#reply_employess\').slideToggle();$(\'#reply_employess_m\').slideToggle();return false;" style="cursor: pointer;"><img src="../img/admin/email_edit.gif">Reply</legend>
				<a onclick="$(\'#reply_employess\').slideToggle();$(\'#reply_employess_m\').slideToggle();return false" href="#" id="reply_employess">
				<b>Click here</b> to reply comment</a>
				<div id="reply_employess_m" style="display: none; ">
					<label>Content: </label>
					<div class="margin-form">
						<textarea cols="100" rows="10" name="reply_employees">'.$reply_employees.'</textarea>
					</div>
					<input type="hidden" name="name_employees" value="'.$name_employee.'" />
					<div class="margin-form">
						<input type="submit" class="button" name="submitAdd'.$this->table.'" value="   Reply   ">
					</div>
				</div>
				
			</fieldset>
			</form>
		</div>';
	}
}
